<template>
  <view class="repair-accept-page">
    <u-navbar title="工单受理" :auto-back="true"></u-navbar>
    
    <view class="content" v-if="orderInfo">
      <!-- 工单信息展示 -->
      <view class="order-info-section">
        <view class="form-card">
          <view class="card-title">工单信息</view>
          <view class="form-content">
            <view class="info-item">
              <text class="info-label">工单编号：</text>
              <text class="info-value">{{ orderInfo.orderNo || '--' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">报修类型：</text>
              <text class="info-value">{{ orderInfo.repairType || '--' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">紧急程度：</text>
              <text class="info-value" :style="{ color: getPriorityColor(orderInfo.urgencyLevel) }">
                {{ getUrgencyText(orderInfo.urgencyLevel) }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 受理信息 -->
      <view class="accept-form-section">
        <view class="form-card">
          <view class="card-title">受理信息</view>
          <view class="form-content">
            <view class="form-item">
              <text class="form-label">受理备注</text>
              <u-textarea 
                v-model="acceptForm.remark" 
                placeholder="请输入受理备注（可选）"
                :maxlength="200"
                :count="true"
                height="120"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 分配维修人员 -->
      <view class="assign-form-section" v-if="orderInfo && orderInfo.status === 1">
        <view class="form-card">
          <view class="card-title">分配维修人员</view>
          <view class="form-content">
            <!-- 选择维修人员 -->
            <view class="form-item">
              <text class="form-label">维修人员</text>
              <view class="picker-wrapper" @click="showRepairmanPicker = true">
                <text class="picker-text">{{ selectedRepairman ? selectedRepairman.name : '请选择维修人员' }}</text>
                <u-icon name="arrow-right" size="16" color="#999"></u-icon>
              </view>
            </view>
            
            <!-- 预计完成时间 - 使用新的公共组件 -->
            <view class="form-item">
              <text class="form-label">预计完成时间</text>
              <DateTimePicker
                v-model="estimatedTime"
                title="选择预计完成时间"
                placeholder="请选择预计完成时间"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onTimeConfirm"
              />
            </view>
            
            <!-- 分配备注 -->
            <view class="form-item">
              <text class="form-label">分配备注</text>
              <u-textarea 
                v-model="assignForm.remark" 
                placeholder="请输入分配备注（可选）"
                :maxlength="200"
                :count="true"
                height="120"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <u-button 
          type="primary" 
          text="受理工单" 
          size="large"
          @click="handleAccept"
          :loading="accepting"
          class="action-button"
        />
      </view>
    </view>

    <!-- 工单信息不存在 -->
    <view class="empty-section" v-else>
      <u-empty 
        text="工单信息不存在" 
        description="请检查工单ID是否正确"
        icon="file-text"
      />
    </view>

    <!-- 维修人员选择器 -->
    <u-picker
      v-model:show="showRepairmanPicker"
      :columns="repairmanColumns"
      @confirm="onRepairmanConfirm"
      @cancel="showRepairmanPicker = false"
      title="选择维修人员"
    />
  </view>
</template>

<script setup>
/**
 * 工单受理页面 - 使用DateTimePicker公共组件示例
 * 
 * 展示如何在工单受理页面中使用新的DateTimePicker公共组件
 * 替换原有的u-datetime-picker实现
 * 
 * @author Wu.Liang
 * @date 2025-01-22
 * @version 1.0.0
 */

import { ref, computed, onMounted } from 'vue'
import { repairWorkApi } from '@/api/repair-work'
import DateTimePicker from '@/components/common/DateTimePicker.vue'

// 页面标题
uni.setNavigationBarTitle({
  title: '工单受理'
})

// 响应式数据
const orderInfo = ref({
  orderNo: 'RO202501220001',
  repairType: '水电维修',
  urgencyLevel: 2,
  status: 1
})

const loading = ref(false)
const accepting = ref(false)
const showRepairmanPicker = ref(false)

// 受理表单
const acceptForm = ref({
  remark: ''
})

// 分配表单
const assignForm = ref({
  remark: ''
})

// 维修人员相关
const selectedRepairman = ref(null)
const estimatedTime = ref('')
const repairmanColumns = ref([
  [
    { label: '张三', value: 1 },
    { label: '李四', value: 2 },
    { label: '王五', value: 3 }
  ]
])

// 计算属性：时间范围限制
const minDate = computed(() => {
  // 最小时间为当前时间
  return new Date().getTime()
})

const maxDate = computed(() => {
  // 最大时间为当前时间+30天
  const date = new Date()
  date.setDate(date.getDate() + 30)
  return date.getTime()
})

// 维修人员选择确认
const onRepairmanConfirm = (e) => {
  console.log('维修人员选择确认:', e)
  const selectedIndex = e.indexs[0]
  const selectedItem = repairmanColumns.value[0][selectedIndex]
  
  selectedRepairman.value = {
    id: selectedItem.value,
    name: selectedItem.label
  }
  
  showRepairmanPicker.value = false
}

// 时间选择确认 - 使用新组件的事件
const onTimeConfirm = (e) => {
  console.log('时间选择确认:', e)
  console.log('选择的时间:', e.value)
  console.log('格式化显示:', e.formatted)
  console.log('时间戳:', e.timestamp)
  
  // 可以在这里添加额外的业务逻辑
  // 比如验证时间是否合理、发送到后端等
}

// 受理工单
const handleAccept = async () => {
  try {
    accepting.value = true
    
    // 验证必填项
    if (!estimatedTime.value) {
      uni.showToast({
        title: '请选择预计完成时间',
        icon: 'none'
      })
      return
    }
    
    // 构建提交数据
    const submitData = {
      orderId: orderInfo.value.id,
      acceptRemark: acceptForm.value.remark,
      repairmanId: selectedRepairman.value?.id,
      estimatedTime: estimatedTime.value,
      assignRemark: assignForm.value.remark
    }
    
    console.log('提交受理数据:', submitData)
    
    // 这里调用实际的API
    // const response = await repairWorkApi.acceptRepairOrder(submitData)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    uni.showToast({
      title: '工单受理成功',
      icon: 'success'
    })
    
    // 返回上一页或跳转到工单列表
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    
  } catch (error) {
    console.error('受理工单失败:', error)
    uni.showToast({
      title: '受理失败，请重试',
      icon: 'error'
    })
  } finally {
    accepting.value = false
  }
}

// 获取紧急程度文本
const getUrgencyText = (urgencyLevel) => {
  const urgencyMap = {
    1: '一般',
    2: '紧急',
    3: '非常紧急'
  }
  return urgencyMap[urgencyLevel] || '一般'
}

// 获取紧急程度颜色
const getPriorityColor = (urgencyLevel) => {
  const colorMap = {
    1: '#999999',  // 一般
    2: '#ff9500',  // 紧急
    3: '#ff4757'   // 非常紧急
  }
  return colorMap[urgencyLevel] || '#999999'
}

// 页面加载
onMounted(() => {
  console.log('工单受理页面加载完成')
  // 这里可以加载工单详情数据
})
</script>

<style lang="scss" scoped>
.repair-accept-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding: 20px;
}

.section {
  margin-bottom: 20px;
}

.form-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.form-content {
  .form-item {
    margin-bottom: 20px;
    
    .form-label {
      display: block;
      font-size: 16px;
      color: #606266;
      margin-bottom: 8px;
      font-weight: 500;
    }
  }
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  .info-label {
    font-size: 14px;
    color: #909399;
    min-width: 80px;
  }
  
  .info-value {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
  }
}

.picker-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  min-height: 44px;
  box-sizing: border-box;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #f5f7fa;
    border-color: #409eff;
  }
  
  .picker-text {
    flex: 1;
    font-size: 16px;
    color: #303133;
    line-height: 20px;
  }
}

.action-section {
  padding: 20px;
  
  .action-button {
    width: 100%;
  }
}

.empty-section {
  padding: 60px 20px;
}

// 响应式设计
@media (max-width: 750px) {
  .content {
    padding: 15px;
  }
  
  .form-card {
    padding: 15px;
  }
  
  .card-title {
    font-size: 16px;
  }
  
  .form-content .form-item .form-label {
    font-size: 15px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    
    .info-label {
      margin-bottom: 5px;
      min-width: auto;
    }
  }
}
</style>
